package cn.ztf.zshop.common.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.util.SaResult;
import cn.ztf.zshop.common.exception.ZShopException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数校验错误:{}", e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
        //TODO 不是很理解为啥是这样获取
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(ZShopException.class)
    public ResponseEntity<String> zShopExceptionHandler(ZShopException zShopException) {
        log.error("ZShopException:{}", zShopException.getMessage());
        if (ObjectUtils.isEmpty(zShopException.getHttpStatus())) {
            zShopException.setHttpStatus(HttpStatus.BAD_REQUEST);
        }
        return ResponseEntity.status(zShopException.getHttpStatus()).body(zShopException.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> globalExceptionHandler(Exception zShopException) {
        log.error("Exception:", zShopException);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(zShopException.getMessage());
    }


    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<String> handlerNotLoginException(NotLoginException nle) throws Exception {
        // 判断场景值，定制化异常信息
        String message = "";
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未提供token";
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token无效";
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token已过期";
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "token已被顶下线";
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "token已被踢下线";
        } else {
            message = "当前会话未登录";
        }
        log.error("NotLoginException:{}", message);
        // 返回给前端
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(message);
    }

}
